import { ControlContainer, FormGroupName } from '@angular/forms';
import { Input, Injector, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { ZoneService, ZoneResource } from '../zone/services/zone.service';
import { APIBase } from '../base/api-base';
import { ActivatedRoute } from '@angular/router';
import { MySelection } from '../base/selection';

export class SelectResourceBase<T> implements OnInit {
  constructor(
    private inject: Injector,
    private resource: ZoneResource,
    private route = inject.get(ActivatedRoute),
    private zone = inject.get(ZoneService),
    public controlContainer: FormGroupName = inject.get(ControlContainer),
  ) {
    const zoneID = this.route.snapshot.queryParamMap.get('id');
    this.dataSource = this.zone.resource(Number(zoneID), resource);
  }
  @Input() preview: APIBase<any, T>;
  dataSource: APIBase<any, T>;
  selection = new MySelection('id');

  ngOnInit() {
    if (this.preview) {
      return;
    }
    const value = this.controlContainer.control.controls['selected'].value;
    this.selection.select(...value);
    this.selection.change.subscribe(() => {
      const arr = [...this.selection.store.values()];
      this.controlContainer.control.controls['selected'].setValue(arr);
    });
  }
}
